package com.xyf.sys.service.impl;

import com.xyf.sys.domain.Region;
import com.xyf.sys.mapper.RegionMapper;
import com.xyf.sys.service.IRegionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author R-H
 * @Date 2024/3/141748
 * @Description
 */
@Slf4j
@Service
public class RegionServiceImpl implements IRegionService {

    @Autowired
    private RegionMapper regionMapper;

    @Override
    public List<Region> regionList() {
        List<Region> regions = regionMapper.selectAll();
        Region region = new Region();
        region.setId(0L);
        regions.add(region);
        return buildTree(regions).get(0).getChildren();
    }

    public static List<Region> buildTree(List<Region> regions) {
        // 创建一个Map，用于根据id查找Region对象
        Map<Long, Region> regionMap = regions.stream()
                .collect(Collectors.toMap(Region::getId, Function.identity()));
        // 遍历所有Region对象，并根据parentId将其添加到父节点的children列表中
        regions.forEach(region -> {
            Long parentId = region.getParentId();
            if (parentId != null && regionMap.containsKey(parentId)) {
                Region parent = regionMap.get(parentId);
                parent.addChild(region);
            }
        });
        // 过滤出所有根节点（即parentId为null的Region对象）
        return regionMap.values().stream()
                .filter(region -> region.getParentId() == null)
                .collect(Collectors.toList());
    }

}
